/**   
* @Title: ProductController.java 
* @Package com.csis.system.controller 
* @Description: TODO
* @author dailey  
* @date 2012-10-7
* @version V1.0   
*/
package com.csis.system.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csis.framework.util.jqgrid.JqGridModel;
import com.csis.framework.util.jqgrid.JqGridUtils;
import com.csis.framework.web.upload.CosUploadHandler;
import com.csis.system.common.IStaticData;
import com.csis.system.common.WebUtil;
import com.csis.system.common.convert.Converter.ConvertArray;
import com.csis.system.domain.Product;
import com.csis.system.domain.ProductFormBean;
import com.csis.system.domain.bean.ProductBeanFormBean;
import com.csis.system.service.CategoryService;
import com.csis.system.service.ProductService;

/**
 * @author dailey
 *
 */
@RequestMapping("/system/prod")
@Controller
public class ProductController {
	protected Log log = LogFactory.getLog(getClass());
	@Resource
	private ProductService productService;

	@Resource
	private CategoryService categoryService;

	@Autowired
	private CosUploadHandler uploadHandler;

	final String BASE_URL = "/system/manager/base/query/";
	final String BASE_URL2 = "/system/manager/admin/prod/";

	@RequestMapping("/toView")
	public String view(Model model, ProductFormBean formBean) {
		Integer id = formBean.getBean().getId();
		Product product = productService.load(id);
		formBean.setBean(product);
		formBean.setCategories(categoryService.getAllCategorys());
		model.addAttribute("formBean", formBean);
		return BASE_URL + "detailprod";
	}

	@RequestMapping("/show")
	public void showPicture(@RequestParam(required = true, defaultValue = "0") Integer id, HttpServletRequest request,
			HttpServletResponse response) {
		byte[] picBytes = null;
		if (id != null) {
			Product product = productService.load(id);
			picBytes = product.getProductImage();
		}
		writeImage(request, response, picBytes);
	}

	private void writeImage(HttpServletRequest request, HttpServletResponse response, byte[] bytes) {
		response.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.  
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).  
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.  
		response.setHeader("Pragma", "no-cache");
		// return a jpeg  
		response.setContentType("image/jpeg");

		try {
			ServletOutputStream out = response.getOutputStream();
			byte[] picBytes = bytes;
			if (picBytes == null || picBytes.length == 0) {
				picBytes = WebUtil.getDefaultProductImage(request);
			}
			out.write(picBytes);
			out.flush();
			out.close();
		} catch (IOException e) {
			log.info(getClass(), e);
		} catch (Exception e) {
			log.info(getClass(), e);
		}
	}

	@RequestMapping("/upload")
	public @ResponseBody
	String uploadPicture(HttpServletRequest request, HttpServletResponse response) {
		String result = "0";
		try {
			uploadHandler.handle(request, response);
			result = "1";
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/toUpload")
	public String getUploadPage() {
		return BASE_URL2 + "upload";
	}

	@RequestMapping("/getUploadImage")
	public void getUploadImage(HttpServletRequest request, HttpServletResponse response) {
		File file = (File) request.getSession().getAttribute(IStaticData.UPLOAD_IAMGE_FILE);
		byte[] bytes = null;
		if (file != null) {
			try {
				bytes = WebUtil.getBytesFromImageFile(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		writeImage(request, response, bytes);
	}

	@RequestMapping("/list")
	public String list() {
		return BASE_URL + "listprod";
	}

	@RequestMapping("/_list")
	public String _list() {
		return BASE_URL2 + "listprod";
	}

	@RequestMapping("/listBy")
	public void listBy(JqGridModel model, HttpServletResponse response) {
		ProductBeanFormBean formBean = WebUtil.buildConvert(model).convertToSingle(ProductBeanFormBean.class);
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter os = null;
		try {
			productService.unionList(formBean);
			os = response.getWriter();
			os.write(JqGridUtils.getJSONParser(ProductBeanFormBean.class).parse(formBean).getContent());
			os.flush();
		} catch (IOException e) {
			if (log.isErrorEnabled())
				log.error(e);
			else
				e.printStackTrace();
		} catch (Exception e) {
			if (log.isErrorEnabled())
				log.error(e);
			else
				e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
		}
	}

	@RequestMapping("/toAdd")
	public String add(Model model, HttpSession session) {
		ProductFormBean formBean = new ProductFormBean();
		Product bean = new Product();
		bean.setProductUpdate(new Date());
		formBean.setCategories(categoryService.getAllCategorys());
		formBean.setBean(bean);
		model.addAttribute("formBean", formBean);
		return BASE_URL2 + "add";
	}

	@RequestMapping("/add")
	public @ResponseBody
	String add(ProductFormBean formBean, HttpSession session) {
		String result = "0";
		Product bean = formBean.getBean();
		//check not empty
		if (StringUtils.isBlank(bean.getProductName()) || (bean.getProductPrice1() == null)
				|| (bean.getProductPrice2() == null) || (bean.getProductPrice3() == null)) {
			return result;
		}
		bean.setProductUpdate(new Date());
		File file = (File) session.getAttribute(IStaticData.UPLOAD_IAMGE_FILE);
		byte[] bytes = null;
		try {
			bytes = WebUtil.getBytesFromImageFile(file);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		bean.setProductImage(bytes);
		try {
			productService.save(bean);
			result = "1";
			if (file != null) {
				file.delete();
				session.setAttribute(IStaticData.UPLOAD_IAMGE_FILE, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/toEdit")
	public String edit(Model model, ProductFormBean formBean) {
		Integer id = formBean.getBean().getId();
		Product bean = productService.load(id);
		formBean.setBean(bean);
		formBean.setCategories(categoryService.getAllCategorys());
		model.addAttribute("formBean", formBean);
		return BASE_URL2 + "modify";
	}

	@RequestMapping("/edit")
	public @ResponseBody
	String edit(ProductFormBean formBean, HttpSession session) {
		String result = "0";
		Product bean = formBean.getBean();
		//check not empty
		if (bean.getId() == null || StringUtils.isBlank(bean.getProductName()) || (bean.getProductPrice1() == null)
				|| (bean.getProductPrice2() == null) || (bean.getProductPrice3() == null)) {
			return result;
		}
		bean.setProductUpdate(new Date());
		File file = (File) session.getAttribute(IStaticData.UPLOAD_IAMGE_FILE);
		byte[] bytes = null;
		try {
			if (file != null) {
				bytes = WebUtil.getBytesFromImageFile(file);
			} else {
				Product product = productService.load(bean.getId());
				if (product != null) {
					bytes = product.getProductImage();
				}
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		bean.setProductImage(bytes);
		try {
			productService.save(bean);
			result = "1";
			if (file != null) {
				file.delete();
				session.setAttribute(IStaticData.UPLOAD_IAMGE_FILE, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/toDel")
	public @ResponseBody
	String remove(ProductFormBean formBean) {
		String beanIds = formBean.getBeanIds();
		ConvertArray<Integer> ids = WebUtil.buildConvert(beanIds.split(",")).convertToArray(int.class);
		try {
			productService.remove(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
		return "1";
	}

}
